package com.icinfo.cloud.provider.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.icinfo.framework.tools.utils.StringUtils;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 行为码工具类
 * @author liyafeng
 * @date 2022/11/9
 * @return {@link null}
 */
public class ActCodeUtils {
    //CODE_WIDTH：二维码宽度，单位像素
    private static final int CODE_WIDTH = 400;
    //CODE_HEIGHT：二维码高度，单位像素
    private static final int CODE_HEIGHT = 400;
    //FRONT_COLOR：二维码前景色，0x000000 表示黑色
    private static final int FRONT_COLOR = 0x000000;
    //BACKGROUND_COLOR：二维码背景色，0xFFFFFF 表示白色
    //演示用 16 进制表示，和前端页面 CSS 的取色是一样的，注意前后景颜色应该对比明显，如常见的黑白
    private static final int BACKGROUND_COLOR = 0xFFFFFF;
    /**
     * 生成二维码
     * @author liyafeng
     * @date 2022/11/9
      * @param content
     * @param outputStream
     * @return
     */
    public static void createQrCodeToOutputStream(String content, OutputStream outputStream) {
        try {
            if (StringUtils.isBlank(content)) {
                return;
            }
            content = content.trim();
            //核心代码-生成二维码
            BufferedImage bufferedImage = getBufferedImage(content);

            //区别就是这一句，输出到输出流中，如果第三个参数是 File，则输出到文件中
            ImageIO.write(bufferedImage, "png", outputStream);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static BufferedImage getBufferedImage(String content) throws WriterException {

        //com.google.zxing.EncodeHintType：编码提示类型,枚举类型
        Map<EncodeHintType, Object> hints = new HashMap();

        //EncodeHintType.CHARACTER_SET：设置字符编码类型
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        //EncodeHintType.ERROR_CORRECTION：设置误差校正
        //ErrorCorrectionLevel：误差校正等级，L = ~7% correction、M = ~15% correction、Q = ~25% correction、H = ~30% correction
        //不设置时，默认为 L 等级，等级不一样，生成的图案不同，但扫描的结果是一样的
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);

        //EncodeHintType.MARGIN：设置二维码边距，单位像素，值越小，二维码距离四周越近
        hints.put(EncodeHintType.MARGIN, 1);

        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, CODE_WIDTH, CODE_HEIGHT, hints);
        BufferedImage bufferedImage = new BufferedImage(CODE_WIDTH, CODE_HEIGHT, BufferedImage.TYPE_INT_BGR);
        for (int x = 0; x < CODE_WIDTH; x++) {
            for (int y = 0; y < CODE_HEIGHT; y++) {
                bufferedImage.setRGB(x, y, bitMatrix.get(x, y) ? FRONT_COLOR : BACKGROUND_COLOR);
            }
        }
        return bufferedImage;
    }

    public static void generateBarCode(String msg, OutputStream outputStream) {
        try {
            generateBarCode128(msg, 10.0, 0.3, true, false, outputStream);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void generateBarCode128(String message, Double height, Double width, boolean withQuietZone, boolean hideText, OutputStream outputStream) {
        Code128Bean bean = new Code128Bean();
        // 分辨率，越大条形码就越大
        int dpi = 150;
        // 设置两侧是否留白
        bean.doQuietZone(withQuietZone);
        // 设置条形码高度和宽度
        bean.setBarHeight(height);
        if (width != null) {
            bean.setModuleWidth(width);
        }
        // 设置文本位置（包括是否显示）
        if (hideText) {
            bean.setMsgPosition(HumanReadablePlacement.HRP_BOTTOM);
        }
        // 设置图片类型
        String format = "image/png";
        BitmapCanvasProvider canvas = new BitmapCanvasProvider(outputStream, format, dpi,
                BufferedImage.TYPE_BYTE_BINARY, false, 0);

        /* 生产条形码 */
        bean.generateBarcode(canvas, message);
        try {
            canvas.finish();
        } catch (IOException e) {
            //ByteArrayOutputStream won't happen
        }
    }

    public static void main(String[] args) {

        FileOutputStream fileOutputStream = null;
        ByteArrayOutputStream out =new ByteArrayOutputStream();
        createQrCodeToOutputStream("https://portal.datacq.com.cn:9443/por/dingtalk.html?redirecturl=http://23.99.94.216:8443/zsba-h5/main-sys/signature-component?userToken=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxODI1ODA1OTQ3NiIsImF1ZCI6IndlYiIsImNyZWF0ZWQiOjE2ODc0OTA2MDc3MTIsImFwcElkIjpudWxsLCJpc3MiOiJpY2luZm8uY24iLCJleHAiOjE2ODgwOTU0MDcsIlNvdXJjZSI6Inh6emYiLCJkZXB0Q29kZSI6IjUwMDEwMDAwMDAwMDEwNzYifQ.L3d6kjsHn3tMuog3VVUiAfcnXKKGf48MKiNF2mPVxQgVQ7qUoZIWrv2ZGnCpcJ4-Aq5RivblZJQVEg0f268W2g&isPcScanCode=1&userName=吴晨皓",out);
        //generateBarCode("030025822192211150001314005",out);
        try {
            fileOutputStream = new FileOutputStream("D:\\qr0300258221922111500013140051.png");
            fileOutputStream.write(out.toByteArray());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
